<template>
  <h1>品牌管理</h1>
  <el-button type="default"
             v-if="authority.brandAdd"
             @click="add">添加品牌</el-button>

  <el-table :data="pageInfo.list"
            stripe
            style="width:100%"
            border
            :header-cell-style="{textAlign:'center'}"
            :cell-style="{textAlign:'center'}">
    <el-table-column prop="id"
                     label="品牌id"></el-table-column>
    <el-table-column prop="name"
                     label="品牌名"></el-table-column>
    <el-table-column prop="logo"
                     label="品牌LOGO">
                  <template v-slot:default="scope">
                  <el-image :src="scope.row.logo"/>
                  </template>
    </el-table-column>
    <el-table-column prop="description"
                     label="品牌介绍"
                     :show-overflow-tooltip="true" width="400px"></el-table-column>
    <el-table-column prop="firstLetter"
                     label="品牌首字母"></el-table-column>
    <el-table-column label="操作"
                     width="350px">
      <template #default="scope">
        <el-button size="small"
                   type="primary"
                   v-if="authority.brandUpdate && scope.row.hot === 0"
                   @click="setHot(scope)">设置为热门品牌</el-button>
        <el-button size="small"
                   type="warning"
                   v-if="authority.brandUpdate && scope.row.hot === 1"
                   @click="unsetHot(scope)">设置非热门品牌</el-button>
        <el-button size="small"
                   type="primary"
                   v-if="authority.brandUpdate"
                   @click="edit(scope)">编辑</el-button>
        <el-button size="small"
                   type="danger"
                   v-if="authority.brandDelete"
                   @click="del(scope)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination class="el-pagination"
                 layout="prev,pager,next,total,jumper,sizes"
                 :total="pageInfo.total"
                 v-model:current-page="pageInfo.pageNum"
                 v-model:page-size="pageInfo.pageSize"
                 :page-sizes="[3,5,10,20]"
                 background
                 @current-change="handleCurrentChange"
                 @size-change="handleSizeChange">
  </el-pagination>

  <el-dialog v-model="disableDialog"
             title="编辑品牌"
             center
             width="600px">
    <el-form :model="brand"
             :rules="rules"
             ref="editBrand"
             label-width="100px">
      <el-form-item label="品牌名"
                    prop="name">
        <el-input placeholder="请输入品牌名"
                  v-model="brand.name"></el-input>
      </el-form-item>
      <el-form-item label="品牌LOGO"
                    prop="logo">
        <el-upload class="avatar-uploader"
                   :action="objectData.host"
                   :data="objectData"
                   ref="updateIcon"
                   :before-upload="getPolicyForUpdate"
                   :auto-upload="false"
                   :on-exceed="exceedHandleUpdate"
                   :on-change="change"
                   :on-success="uploadSuccess"
                   :on-error="uploadFail"
                   :limit="1">
          <template #trigger>
            <el-button type="primary">选择一个图片文件</el-button>
          </template>
          <template #tip>
            <div class="el-upload__tip"
                 style="color:red">
              只能上传一张图片，第二张会覆盖第一张图片
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="品牌描述"
                    prop="description">
        <el-input autosize
                  type="textarea"
                  placeholder="请添加品牌描述"
                  v-model="brand.description"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="cancelSave">取消</el-button>
      <el-button type="primary"
                 @click="saveData('editBrand')">保存</el-button>
    </template>
  </el-dialog>

  <el-dialog v-model="addDisableDialog"
             title="添加品牌"
             center
             width="600px">
    <el-form :model="brand"
             :rules="rules"
             ref="addBrand"
             label-width="100px">
      <el-form-item label="品牌名"
                    prop="name">
        <el-input type="text"
                  placeholder="请输入品牌名"
                  v-model="brand.name"></el-input>
      </el-form-item>
      <el-form-item label="品牌LOGO">
        <el-upload class="avatar-uploader"
                   :action="objectData.host"
                   :data="objectData"
                   ref="uploadIcon"
                   :before-upload="getPolicyForUpdate"
                   :auto-upload="false"
                   :on-exceed="exceedHandle"
                   :on-change="change"
                   :on-success="uploadSuccess"
                   :on-error="uploadFail"
                   :limit="1">
          <template #trigger>
            <el-button type="primary">选择一个图片文件</el-button>
          </template>
          <template #tip>
            <div class="el-upload__tip"
                 style="color:red">
              只能上传一张图片，第二张会覆盖第一张图片
            </div>
          </template>
        </el-upload>

      </el-form-item>
      <el-form-item label="品牌描述"
                    prop="description">
        <el-input autosize
                  type="textarea"
                  placeholder="请添加品牌描述"
                  v-model="brand.description"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="cancelSave">取消</el-button>
      <el-button type="primary"
                 @click="saveData('addBrand')">添加</el-button>
    </template>
  </el-dialog>
</template>

<script  >
import { ref } from 'vue';
import { genFileId } from 'element-plus'
export default {
  setup () {
    const uploadIcon = ref(null)
    const updateIcon = ref(null)
    const exceedHandle = (files) => {
      uploadIcon.value.clearFiles()
      const file = files[0]
      file.uid = genFileId()
      uploadIcon.value.handleStart(file)
    }
    const exceedHandleUpdate = (files) => {
      updateIcon.value.clearFiles()
      const file = files[0]
      file.uid = genFileId()
      updateIcon.value.handleStart(file)
    }
    return { uploadIcon, exceedHandle, exceedHandleUpdate, updateIcon }
  },
  data () {
    let checkBrandNameValidate = (rule, value, callback) => {
      let url = this.$url.PmsBrandControllerBaseUrl + "/checkBrandName";
      this.$http.post(url, value).then(res => {
        if (res.data.data) {
          callback(new Error("品牌名已存在"));
        } else {
          callback();
        }
      });
    };
    return {
      authority: {
        total: false,
        brandAdd: false,
        brandUpdate: false,
        brandDelete: false
      },
      objectData: {

      },
      logoUrl: '',
      brandId: '',
      fileList: [],
      addDisableDialog: false,
      disableDialog: false,
      pageInfo: {
        pageNum: 1,
        pageSize: 5,
      },
      brand: {

      },
      rules: {
        name: [
          { required: true, message: "请输入品牌名", trigger: ['blur', 'change'] },
          { min: 1, max: 10, message: '品牌名长度必须在1-10个字符之间', trigger: ['blur', 'change'] },
          { validator: checkBrandNameValidate, trigger: 'blur' }
        ],
        description: [
          { required: true, message: "请输入品牌描述", trigger: ['blur', 'change'] },
          { min: 1, max: 100, message: '品牌描述不能超过100个字符', trigger: ['blur', 'change'] },
        ],
      },
    }
  },
  methods: {
    initAuthority () {
      this.authority.total = this.$store.state.authority[this.$power.map.get("商品管理-品牌管理").property]
      this.authority.brandAdd = this.$store.state.authority[this.$power.map.get("商品管理-品牌管理-添加").property]
      this.authority.brandUpdate = this.$store.state.authority[this.$power.map.get("商品管理-品牌管理-修改").property]
      this.authority.brandDelete = this.$store.state.authority[this.$power.map.get("商品管理-品牌管理-删除").property]
      Object.freeze(this.authority)
      this.$power.totalCheckAuthority(this.authority)
    },
    showData () {
      let params = {
        pageNum: this.pageInfo.pageNum,
        pageSize: this.pageInfo.pageSize
      }
      let url = this.$url.PmsBrandControllerBaseUrl + "/getPaged";
      this.$http.get(url, { params: params }).then(res => {
        this.pageInfo = res.data.data;
      })
    },
    handleCurrentChange () {
      this.showData();
    },
    handleSizeChange () {
      this.showData();
    },
    del (scope) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let url = this.$url.PmsBrandControllerBaseUrl + `/check/deleteBrand?id=${scope.row.id}`;
        this.$http.delete(url).then(res => {
          if (res.data.code == 2000) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          } else {
            this.$message({
              type: 'error',
              message: res.data.message
            });
          }
          this.showData();
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    edit (scope) {
      if (this.fileList.length > 0 && this.updateIcon) {
        this.updateIcon.handleRemove(this.fileList[0])
      }
      this.logoUrl = ''
      this.disableDialog = true;
      this.index = scope.$index;
      this.brand = {};
      this.brand = { ...scope.row };
      this.brandId = this.brand.id
    },
    saveData (ref_name) {
      this.$refs[ref_name].validate((valid) => {
        if (valid) {
          if (this.disableDialog) {
            this.$confirm("数据即将保存，是否确认？", "提示", {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              let url = this.$url.PmsBrandControllerBaseUrl + "/check/update";
              this.$http.post(url, this.brand).then(res => {
                if (res.data.code === 2000) {
                  this.$message({
                    type: 'success',
                    message: '保存成功!'
                  });
                  this.showData();
                  this.disableDialog = false;
                  this.brand = {};
                  if (this.fileList.length > 0) {
                    this.updateIcon.submit()
                  }
                } else {
                  this.$message({
                    type: 'error',
                    message: res.data.message
                  });
                }
              })
            })
          }
          if (this.addDisableDialog) {
            this.$confirm("数据即将保存并添加，是否确认？", "提示", {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              let url = this.$url.PmsBrandControllerBaseUrl + "/check/insert";
              this.$http.post(url, this.brand).then(res => {
                if (res.data.code === 2000) {
                  this.$message({
                    type: 'success',
                    message: '添加成功!'
                  });
                  this.addDisableDialog = false;
                  this.brand = {};
                  this.pageInfo.pageNum = 1;
                  this.brandId = `${res.data.data}`
                  if (this.fileList.length == 0) {
                    this.showData()
                  } else {
                    this.uploadIcon.submit()
                  }
                } else {
                  this.$message({
                    type: 'error',
                    message: res.data.message
                  });
                }
              })
            })
          }
        }
      })
    },
    cancelSave () {
      if (this.disableDialog) {
        this.mes = "已取消保存"
      }
      if (this.addDisableDialog) {
        this.mes = "已取消添加"
      }
      this.$confirm("数据尚未保存，是否取消？", "提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.disableDialog) {
          this.disableDialog = false;
        }
        if (this.addDisableDialog) {
          this.addDisableDialog = false;
        }
        this.user = {}
        this.$message({
          type: 'info',
          message: this.mes
        });
      })
    },
    add () {
      if (this.fileList.length > 0 && this.uploadIcon) {
        this.uploadIcon.handleRemove(this.fileList[0])
      }
      this.brandId = ''
      this.logoUrl = ''
      this.addDisableDialog = true;
      this.brand = {};
    },
    change (file, fileList) {
      this.fileList = fileList
    },
    getPolicyForCreate () {
      return new Promise(((resolve, reject) => {
        this.$http.get(this.$url.OSSControllerBaseUrl + '/getPolicyForBrandIcon', {
          params: {
            brandId: this.brandId
          }
        })
          .then(res => {
            this.objectData.OSSAccessKeyId = res.data.data.accessid; // Bucket拥有者的AccessKey ID。
            this.objectData.policy = res.data.data.policy; //Policy规定了请求表单域的合法性。
            this.objectData.Signature = res.data.data.signature;//根据AccessKey Secret和Policy计算的签名信息，OSS验证该签名信息从而验证该Post请求的合法性。
            this.objectData.dir = res.data.data.dir;//前缀
            this.objectData.host = res.data.data.host;// "https://" + bucketname + '.' + endpoint;  (前端请求oss服务路径)
            this.objectData.key = res.data.data.key;//dir + fileName (上传Object的名称。)
            this.logoUrl = this.objectData.host + '/' + this.objectData.dir + this.brandId
            resolve(true)
          })
          .catch(err => {
            console.log(err);
            reject(false)
          })
      }))
    },
    uploadSuccess () {
      this.updateUrl()

    },
    uploadFail () {
      this.$message({
        message: "上传失败",
        type: "error"
      })
    },
    updateUrl () {
      let data = {
        id: Number(this.brandId),
        logo: this.logoUrl
      }
      this.$http.post(this.$url.PmsBrandControllerBaseUrl + '/check/updateLogo', data)
        .then((res) => {
          if (res.data.code === 2000) {
            this.$message({
              message: "上传成功",
              type: "success"
            })
            this.showData()
          } else {
            this.$message({
              message: "URL更新出错",
              type: "error"
            })
          }

        })
    },
    getPolicyForUpdate () {
      return new Promise(((resolve, reject) => {
        this.$http.get(this.$url.OSSControllerBaseUrl + '/getPolicyForBrandIcon', {
          params: {
            brandId: this.brandId
          }
        })
          .then(res => {
            this.objectData.OSSAccessKeyId = res.data.data.accessid; // Bucket拥有者的AccessKey ID。
            this.objectData.policy = res.data.data.policy; //Policy规定了请求表单域的合法性。
            this.objectData.Signature = res.data.data.signature;//根据AccessKey Secret和Policy计算的签名信息，OSS验证该签名信息从而验证该Post请求的合法性。
            this.objectData.dir = res.data.data.dir;//前缀
            this.objectData.host = res.data.data.host;// "https://" + bucketname + '.' + endpoint;  (前端请求oss服务路径)
            this.objectData.key = res.data.data.key;//dir + fileName (上传Object的名称。)
            this.logoUrl = this.objectData.host + '/' + this.objectData.dir + this.brandId
            resolve(true)
          })
          .catch(err => {
            console.log(err);
            reject(false)
          })
      }))
    },
    setHot(scope){
      this.$http.get(this.$url.PmsBrandControllerBaseUrl + '/check/setHot',{
        params:{
          id:scope.row.id,
          hot:1
        }
      })
      .then(res=>{
        if(res.data.code === 2000){
          this.$message({
            message:'已经将该品牌设置为热门',
            type:"success"
          })
          this.showData()
        }else{
          this.$message({
            message:res.data.message,
            type:"error"
          })
        }
      })
    },
    unsetHot(scope){
      this.$http.get(this.$url.PmsBrandControllerBaseUrl + '/check/setHot',{
        params:{
          id:scope.row.id,
          hot:0
        }
      })
      .then(res=>{
        if(res.data.code === 2000){
          this.$message({
            message:'已经将该品牌设置为热门',
            type:"success"
          })
          this.showData()
        }else{
          this.$message({
            message:res.data.message,
            type:"error"
          })
        }
      })
    }
  },
  created () {
    this.showData();
    this.initAuthority()
  }
}
</script>

<style scope>
el-pagination {
  text-align: center;
  margin-top: 20px;
}
.inline-block {
  display: inline-block;
}
.margin-right-10 {
  margin-right: 15px;
}
</style>